var PostMessageUtils = function () {
    return this;
};
PostMessageUtils.prototype = {
    constructor: PostMessageUtils,
    /**
     * 发送消息.
     * @param msgType 消息管道.
     * @param data 内容.
     * @param object iframe dom source.
     */
    send: function (msgType, data, object) {
        const iframeWindow = object.contentWindow;
        const target = object.src;
        const messageSource = {
            type: msgType,
            data: data
        };
        const message = JSON.stringify(messageSource);
        iframeWindow.postMessage(message, target);
    },

    /**
     * 给父窗体发送消息.
     * @param msgType 消息管道.
     * @param data 内容.
     */
    sendToParent: function (msgType, data) {
        const messageSource = {
            type: msgType,
            data: data
        };
        const message = JSON.stringify(messageSource);
        parent.postMessage(message, '*');
        console.log('send message:', messageSource);
    },

    /**
     * 监听对象方法映射图
     */
    _listenMap: {},

    /**
     * 添加监听.
     * @param msgType 消息管道.
     * @param fun 解析方法.
     */
    addListen: function (msgType, fun) {
        this._listenMap[msgType] = fun;
        return this;
    },

    /**
     * 开启监听.
     * @param origin 监听消息来源.
     */
    startListen: function (origin) {
        const self = this;
        /**
         * 消息处理.
         * @param event
         */
        const handleMessage = function (event) {
            event = event || window.event;
            console.log('accepted message:', JSON.parse(event.data));

            if(event.origin === origin) {
                const messageSource = event.data;
                const message = JSON.parse(messageSource);
                if (self._listenMap[message.type]) {
                    const fun = self._listenMap[message.type];
                    fun(message.data);
                }
            }
        };

        //处理
        if (window.addEventListener) {
            window.addEventListener("message", handleMessage, false);
        } else {
            window.attachEvent("onmessage", handleMessage);
        }
    },

    /**
     * 获取引用源地址头.
     * @returns {string}
     */
    getSourceUrl: function () {
        const url = document.referrer;
        const startPos = url.indexOf('//') + 2;
        return url.substr(0, url.indexOf('/', startPos));
    }
};
window.QiPostMessageUtils = new RestClientUtils();